package com.example.zookeeper.threadlocal;

import com.google.common.collect.Lists;

import java.util.List;

/**
 * Created by ZMJ on 2020/1/3.
 */
public class UseThreadLocal {

    // 会多处判断是否在黑名单里面
    public void isUserName(String userName) {
        // init- ThreadLocal
        this.initThreadLocal();

        try {
            // 是否在黑名单里面 - >get使用
            this.dealUserServiceDeal(userName);
        } catch (Exception e) {
            // ...
        } finally {
            // 使用完必须删除, 防止内存泄漏
            this.removeThreadLocal();
        }
    }

    // 是否在黑名单里面
    private boolean dealUserServiceDeal(String userName) {
        List<String> blackList = getThreadLocal();
        if (blackList.contains(userName)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    // 初始化
    private void initThreadLocal() {
        List<String> blackList = BlackListContext.userListThreadLocal.get();
        if (blackList == null) {
            blackList = Lists.newArrayList();
            BlackListContext.userListThreadLocal.set(blackList);
        }
        blackList.add("张三");
        blackList.add("李四");
    }

    // 获取
    private List<String> getThreadLocal() {
        return BlackListContext.userListThreadLocal.get();
    }

    // 删除
    private void removeThreadLocal() {
        BlackListContext.userListThreadLocal.remove();
    }
}
